import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:yp/helper.dart';
import 'package:yp/services/api.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';

import 'state.dart';

class BindWelfareCardLogic extends GetxController {

  final BindWelfareCardState state = BindWelfareCardState();
  final TextEditingController cardNumberTextEditingController = TextEditingController();
  final TextEditingController passwordTextEditingController = TextEditingController();

  /// 绑定福利卡
  void bindBindWelfareCard() {
    if (cardNumberTextEditingController.text.isEmpty) {
      toast("请输入11位福利卡卡号");
      return;
    }
    if (cardNumberTextEditingController.text.length != 11) {
      toast("请输入11位福利卡卡号");
      return;
    }
    if (passwordTextEditingController.text.isEmpty) {
      toast("请输入密码");
      return;
    }
    var bytes = utf8.encode(passwordTextEditingController.text); // data being hashed
    var digest = sha1.convert(bytes);
    Map<String, dynamic> params = {
      "use_platform": 2,
      "user_num_id:": SpUtil.getInt('empeNumId'),
      "access_token": SpUtil.getString('token'),
      "card_no": cardNumberTextEditingController.text,
      "password": digest.toString()
    };

    EasyLoading.show();
    Api.bindWelfareCard(params).listen((event) {
      EasyLoading.dismiss();
      print("绑定福利卡：$event");
      if (event["code"] == 0) {
        EasyLoading.showSuccess("绑定成功");
        Get.back(result: () {});
      }
    });
  }

  void setPasswordShow() {
    state.passwordShow = !state.passwordShow;
    update();
  }
}
